﻿using glTech.Log4netWrapper;
using Nancy;
using RESTFinder.Service.Extensions;
using RESTFinder.Service.Models;
using RESTFinder.Service.Utils;
using System;
using System.IO;
using System.Linq;

namespace RESTFinder.Service
{
    public class DocumentHandler : RavenModule
    {
        public DocumentHandler(Domains.IDocumentDomain documentDomain)
            : base("")
        {
            Get["/crossdomain.xml"] = x =>
            {
                return Response.AsXml("");
            };
            Get["/document/"] = p =>
            {
                return View["document"];
            };

            Get["/document/folders"] = p =>
            {
                return null;
            };
       
            Get["/document/fileupload"] = x =>
            {
                return View["FileUpload"];
            };
            Post["/document/fileupload"] = x =>
            {
                try
                {
                    string guid = this.Request.Form.guid;
                    string id = this.Request.Form.id;
                    string name = this.Request.Form.name;
                    string type = this.Request.Form.type;
                    string lastModifiedDate = this.Request.Form.lastModifiedDate;
                    string size = this.Request.Form.size;
                    string chunks = this.Request.Form.chunks;
                    string strchunk = this.Request.Form.chunk;
                    string fileMd5 = this.Request.Form.fileMd5;

                    string qycode = this.Request.Form.qyCode;
                    if(!string.IsNullOrEmpty( qycode))
                    {
                        qycode = qycode.Trim('\'');
                    }

                    int chunkcount = 0,chunk;
                    if (!string.IsNullOrEmpty(chunks) && int.TryParse(chunks, out chunkcount) && chunkcount > 1 && int.TryParse(strchunk,out chunk))
                    {
                        //属于分片文件
                        var file = this.Request.Files.FirstOrDefault();
                        if (file != null)
                        {
                            var md5 = documentDomain.PushChunk(fileMd5, chunk, file.Name, Path.GetExtension(file.Name), file.ContentType, file.Value);
                            return Response.AsJson(md5);
                        }
                    }
                    else
                    {
                        var file = this.Request.Files.FirstOrDefault();
                        if (file != null)
                        {
                            var md5 = documentDomain.Push(file.Name, System.IO.Path.GetExtension(file.Name), file.ContentType, file.Value,qycode);
                            return Response.AsJson(md5);
                        }
                    }
                    return Response.AsRedirect("/document");
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex.Message.ToString());
                    return Response.AsRedirect("/document");
                }


            };

            Post["/document/fileupload/checkwholefile"] = p =>
            {
                var md5Client = this.Request.Form.md5;

                //MD5值验证
                string md5 = md5Client.Value.ToLower();
                var result = documentDomain.Exist(md5);


                return Response.AsJson(result);
            };

            Post["/document/fileupload/fileMerge"] = p =>
            {
                string fileMd5 = this.Request.Form.fileMd5;
                string ext = this.Request.Form.ext;
                string name = this.Request.Form.name;
                string contentType = this.Request.Form.contentType;

                if (!ext.StartsWith(".")) ext = "." + ext;
                var result = documentDomain.FileMerge(fileMd5,name, contentType, ext);

                return Response.AsJson(result);
            };
            

            Post["/document/preview"] = x =>
            {
                return Response.AsJson("");
            };

            Get["/document/info/{id}"] = p =>
            {
                string id = p.id;
                if (!string.IsNullOrEmpty(id) && id.Contains(","))
                {
                    var md5s = id.Split(',');

                    var documents = documentDomain.Fetch(md5s);

                    if (documents != null && documents.Any())
                    {
                        return Response.AsJson(documents.Select(document => new
                        {
                            md5 = document.md5,
                            name = document.name,
                            extension = document.extension,
                            mimetype = document.contenttype,
                            rdate = document.rdate
                        }));
                    }
                    return "找不到该文档 " + p.id;
                }
                else
                {
                    var document = documentDomain.Fetch(p.id);

                    if (document == null)
                        return "找不到该文档 " + p.id;

                    return Response.AsJson(new
                    {
                        md5 = document.md5,
                        name = document.name,
                        extension = document.extension,
                        mimetype = document.contenttype,
                        rdate = document.rdate
                    });
                }
            };

            Get["/document/{id}"] = p =>
            {
                string id = p.id;
                if (!string.IsNullOrEmpty(id) && id.Contains(","))
                {
                    var md5s = id.Split(',');

                    var documents = documentDomain.Fetch(md5s);

                    if (documents != null && documents.Any())
                    {
                        //压缩，并返回
                        var mimeType = "application/zip";
                        var extension = "zip";
                        var name = "打包下载的文件";
                        var file = documentDomain.Compress(documents);
                        return Response.AsFile(file, mimeType, extension, name);
                    }
                    else
                    {
                        return "找不到该文档 " + p.id;
                    }
                }
                else
                {
                    var document = documentDomain.Fetch(p.id);

                    if (document == null)
                        return "找不到该文档 " + p.id;

                    string mimeType = document.contenttype;
                    string extension = document.extension;
                    string file = document.file;
                    string name = document.name;

                    return Response.AsFile(file, mimeType, extension, name);
                }
            };

            Post["/document/zipfolder"] = p =>
            {
                var data = Request.Form.data;

                string md5 = "";
                if (data)
                {
                    SubFolderModel subFolderModel = Newtonsoft.Json.JsonConvert.DeserializeObject<SubFolderModel>(data);

                    var zipItems = subFolderModel.GetZipEntryItems().ToArray();
                    var md5s = zipItems.Select(o => o.Item1).ToArray();
                    var documents = documentDomain.Fetch(md5s);
                    if (documents != null && documents.Any())
                    {
                        md5 = documentDomain.CompressNestedFolder(documents, zipItems);
                    }
                }

                return md5;
            };


            Get["/document/zipfile/{md5}"] = p =>
            {

                string md5 = p.md5;
                var filename = documentDomain.GetZipFile(md5);
                var mimeType = "application/zip";
                var extension = "zip";
                var name = "打包下载的文件";
                return Response.AsFile(filename, mimeType, extension, name);
            };

            Post["/document/nestedfolder"] = p =>
            {
                var data = Request.Form.data;
                if (data)
                {
                    SubFolderModel subFolderModel = Newtonsoft.Json.JsonConvert.DeserializeObject<SubFolderModel>(data);

                    var zipItems = subFolderModel.GetZipEntryItems().ToArray();
                    var md5s = zipItems.Select(o => o.Item1).ToArray();
                    var documents = documentDomain.Fetch(md5s);
                    if (documents != null && documents.Any())
                    {
                        //压缩，并返回
                        var mimeType = "application/zip";
                        var extension = "zip";
                        var name = subFolderModel.Name;
                        string file = documentDomain.CompressNestedFolder(documents, zipItems);
                        return Response.AsFile(file, mimeType, extension, name);
                    }
                    else
                    {
                        return "找不到该文档 " + subFolderModel.Name;
                    }
                }
                return "";
            };
        }
    }

    public class StreamResponse : Response
    {
        public StreamResponse(Func<Stream> readStream, string contentType)
        {
            Contents = stream =>
            {
                using (var read = readStream())
                {
                    read.CopyTo(stream);
                }
            };
            ContentType = contentType;
            StatusCode = HttpStatusCode.OK;
        }
    }
}
